package com.hunantv.mglive.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.data.advert.AdvertData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2016/2/19.
 */
public class AdvertPreference {
    private static AdvertPreference advertPreference;
    private SharedPreferences sharedPreferences;
    private static final String TOKEN_KEY = "advert_info";

    public static AdvertPreference getInstance(Context context){
        if(advertPreference == null)
        {
            advertPreference = new AdvertPreference(context);
        }
        return advertPreference;
    }

    private AdvertPreference(Context context){
        sharedPreferences = context.getSharedPreferences(context.getPackageName() + "advert_info", Context.MODE_PRIVATE);
    }

    public void saveAdvert(String url,byte[] bytes){
        if(url == null)
        {
            return;
        }
        if(!isSave(url)){
            List<AdvertData> advertDatas = getAdverts();
            if(advertDatas == null)
            {
                advertDatas = new ArrayList<AdvertData>();
            }
            if(advertDatas.size() >= 10)
            {
                //超出,截取
                advertDatas = advertDatas.subList(advertDatas.size()-10,advertDatas.size() - 1);
            }
            AdvertData data  = new AdvertData();
            data.setUrl(url);
            data.setBytes(bytes);
            advertDatas.add(data);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(TOKEN_KEY,JSON.toJSONString(advertDatas));
            editor.commit();
        }
    }

    public byte[] getAdvertByUrl(String url){
        List<AdvertData> advertDatas = getAdverts();
        if(advertDatas != null && url != null)
        {
            for (int i=0;i<advertDatas.size();i++){
                AdvertData data = advertDatas.get(i);
                if(data.getUrl().equals(url))
                {
                    return data.getBytes();
                }
            }
        }

        return null;
    }

    public List<AdvertData> getAdverts(){
        String infoJson = sharedPreferences.getString(TOKEN_KEY, "");
        return StringUtil.isNullorEmpty(infoJson) ? null : JSON.parseArray(infoJson,AdvertData.class);
    }

    public boolean isSave(String url){
        List<AdvertData> advertDatas = getAdverts();
        if(advertDatas == null)
        {
            advertDatas  = new ArrayList<AdvertData>();
        }
        for (AdvertData data : advertDatas){
            if(url.equals(data.getUrl())){
                //已存在,忽略
                return true;
            }
        }
        return false;
    }

}
